<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2021/07/16
 * Time: 17:33
 * @link http://www.lmterp.cn
 */

namespace app\common\model;

use think\model\relation\HasMany;

class OrdersPick extends BaseModel
{
    protected $pk = 'pick_id';

    protected $insert = ['create_by', 'update_by'];

    protected $update = ['update_by'];

    /**
     * 一对多关联拣货单详情
     * @return HasMany
     * @date 2021/07/16
     * @author longli
     */
    public function info()
    {
        return $this->hasMany(OrdersPickInfo::class, 'pick_id', 'pick_id');
    }

    /**
     * 关联管理员
     * @return \think\model\relation\BelongsTo
     * @date 2021/04/05
     * @author longli
     */
    public function admin()
    {
        return $this->belongsTo(Admin::class, "create_by", "id");
    }

    /**
     * 通过 SKU 匹配拣货单
     * @param array $skuList
     * @return OrdersPickInfo|null
     * @date 2021/07/16
     * @author longli
     */
    public function findPick($skuList = [])
    {
        foreach($this->info()->where("print_user", "eq", 0)->select() as $pick)
        {
            $diff = array_column($pick->goods, 'qty', 'sku');
            if($diff == $skuList) return $pick;
        }
    }

    /**
     * 拣货单是否完成
     * @return bool
     * @date 2021/07/17
     * @author longli
     */
    public function isEnd()
    {
        if($this->is_end == self::IS_YES) return true;
        if(!$this->info()->where("print_user", "eq", 0)->count())
        {
            $this->is_end = self::IS_YES;
            $this->save();
        }
        return $this->is_end == self::IS_YES;
    }
}
